package br.com.robot.implement.steam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import br.com.model.SeedsToNavigate;
import br.com.model.dao.DAOFactory;
import br.com.robot.RobotBean;
import br.com.robot.RobotConfigurationBasic;
import br.com.robot.RobotController;
import br.com.robot.RobotList;
import br.com.robot.implement.AbstractRobot;
import br.com.util.ER;
import br.com.util.Web;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;

public class Steam  extends AbstractRobot
{
	@Override
	public void onStart( )
	{
		super.onStart( );
		
		setApenasPaginas( );
	}
	
	@Override
	public boolean shouldVisit( WebURL url ) 
	{
		return super.shouldVisit( url );
	}
	
	@Override
	public List<String> configuraSeeds() 
	{
		List<String> lst = new ArrayList<String>( );
		
		try 
		{
			String buscaExprecao = ER.buscaExprecao( Web.novaInstacia( ).get( "http://store.steampowered.com/search/results?sort_order=ASC&page=1" ), 
					 "\\.\\.\\..*?<a href.*?>(.*?)</" );
			int totalPaginas = Integer.parseInt( buscaExprecao );
			
			for( int i = 1; i <= totalPaginas; i++ )
				lst.add( "http://store.steampowered.com/search/results?sort_order=ASC&page=" + i );
		} 
		catch( ClientProtocolException e )
		{
			e.printStackTrace( );
		} 
		catch( IOException e )
		{
			e.printStackTrace( );
		}

		return lst;
	}
	
	@Override
	public void visit( Page page )
	{
		if( page.getParseData( ) instanceof HtmlParseData ) 
		{
			List<WebURL> links = ((HtmlParseData)page.getParseData( )).getOutgoingUrls( );

			for( WebURL webURL : links )
			{
				if( webURL.getURL( ).matches( "http://store.steampowered.com/app/\\d*/\\?snr=.*$" ) )
				{
					SeedsToNavigate stn = new SeedsToNavigate( );
					stn.setRobo( "" + RobotList.ID_STEAM_ROBOT       );
					stn.setUrl ( Web.cleanParans( webURL.getURL( ) ) );
					
					if( DAOFactory.infDao( ).save( stn ) )
						System.out.println( "Salvo game!" + stn.getUrl( ) );
				}
			}
		}
	}

	@Override
	public RobotConfigurationBasic infConfig() 
	{
		RobotConfigurationBasic configs = new RobotConfigurationBasic( )
			.setFollowRedirect  ( true                        )
			.setNumeroCrawllersm( 100                         )
			.setProfundidade    ( 0                           )
			.setRobots          ( Arrays.asList( infBean( ) ) );
	
		return configs;
	}

	@Override
	public RobotBean<? extends AbstractRobot> infBean()
	{
		return RobotList.getBean( RobotList.ID_STEAM_ROBOT );
	}
	
	@Override
	public void onFinalize( )
	{
		super.onFinalize();
		
		RobotController.infController( ).executa( Steam_Games.class );
	}
}